import React, { useRef, useEffect } from 'react';
import './scroll-pager.css';

interface Props {
  totalRows: number;
  pageSize: number;
  currentPage: number;
  onChangePage: (page: number) => void;
}

export default function ScrollPager({
  totalRows,
  pageSize,
  currentPage,
  onChangePage,
}: Props) {
  const totalPages = Math.ceil(totalRows / pageSize);
  const trackRef = useRef<HTMLDivElement>(null);

  // 当 page 变化时，让滚动条自动对准
  useEffect(() => {
    if (trackRef.current) {
      const top = (currentPage / totalPages) * trackRef.current.scrollHeight;
      trackRef.current.scrollTop = top;
    }
  }, [currentPage, totalPages]);

  // 根据滚动条位置反向计算页码
  const handleScroll = () => {
    if (trackRef.current) {
      const { scrollTop, scrollHeight } = trackRef.current;
      const raw = (scrollTop / scrollHeight) * totalPages;
      const page = Math.min(totalPages - 1, Math.max(0, Math.round(raw)));
      if (page !== currentPage) onChangePage(page);
    }
  };

  return (
    <div
      ref={trackRef}
      className="scroll-pager"
      onScroll={handleScroll}
    >
      {Array.from({ length: totalPages }).map((_, p) => (
        <div
          key={p}
          className={`pager-block ${p === currentPage ? 'active' : ''}`}
          onClick={() => onChangePage(p)}
        >
          {p + 1}
        </div>
      ))}
    </div>
  );
}